<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use App\Models\GoldSeed;
use App\Models\GoldRound;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;

class GoldSeedSplitsController extends AdminController
{
    protected $title = '金店商品种子拆单';
    
    protected function seed($id = null)
    {
    	$seedId = $id ?? request('seed_id');
    	if (! $seed = GoldSeed::find($seedId)) {
    		return back()->with(admin_error('必须依附于商品种子主体'));
	    }
    	return $seed;
    }
    
    public function edit($id, Content $content)
    {
	    return $content
		    ->title($this->title)
		    ->description($this->description['edit'] ?? trans('admin.edit'))
		    ->body($this->form($id)->edit($id));
    }
	
    protected function form($id = null)
    {
        $form = new Form(new GoldSeed());
        
        $seed = $this->seed($id);
	
	    $form->hasMany('goldseedsplits', "SEED: {$seed->title}", function (Form\NestedForm $form) {
		    
	    	$form->select('split_gold_seed_id', '拆单种子')
			    ->options(GoldSeed::all()->pluck('title', 'id'))
			    ->rules('required');
	    	
	    	$form->select('split_gold_round_id', '拆单场次')
			    ->options(GoldRound::all()->pluck('title', 'id'))
			    ->rules('required')
			    ->help('NOTE: 拆单后进入对应场次');
	    });
     
	    $this->formTools($form);
	    $this->formSaving($form);
	    $this->formSaved($form);
	
	    $form->setAction("/admin/gold-seed-splits/{$id}?seed_id={$id}");

        return $form;
    }
	
	protected function formTools(Form $form)
	{
		$form->tools(function (Form\Tools $tools) {
			$tools->disableList();
			$tools->disableView();
			$tools->disableDelete();
			$tools->prepend('
		        <a
                    href="'.route('admin.gold-seeds.index').'"
                    class="btn btn-sm btn-default" style="margin-right: 5px">
                    <i class="fa fa-list"></i> 列表
                </a>
	        ');
		});
	}
	
	protected function formSaving(Form $form)
	{
		$form->saving(function (Form $form) {
			$seed = $form->model();
			if (has_locking_gold_seed($seed)
				and $form->isEditing()) {
				admin_error('当前种子正在金店金店活动中...不可更改!');
				return redirect('admin/gold-seeds');
			}
			return true;
		});
	}
	
	protected function formSaved(Form $form)
	{
		$form->saved(function () {
			return redirect(route('admin.gold-seeds.index'));
		});
	}
}
